package quitDispos

import (
	"database/sql"
	"db2s/Er"
	"db2s/arg"
	"db2s/global"
	"db2s/outPut"
	"encoding/json"
	"fmt"
	"os"
	"os/signal"
	"syscall"
)

type DestDbConnection struct {
	Name  string             `json:"name"`
	Drive string             `json:"drive"`
	Jdbc  string             `json:"jdbc"`
	DsnS  map[string]*sql.DB `json:"dsns"`
}

type CloseFileFin struct {
	FileFin []*os.File
	XlsFin  outPut.Result
}
type Close struct {
	Dsn       DestDbConnection `json:"dsn"`
	closeFin  CloseFileFin
	Event     string
	CheckMode string `json:"mode"`
}

// AbnormalExit 终端通过Ctrl+C信号、kill、kill -9 结束进程时进行善后处理
func (c Close) AbnormalExit() {
	signalChan := make(chan os.Signal, 1)
	// 将os.Interrupt、syscall.SIGTERM和syscall.SIGKILL信号发送到signalChan通道
	signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
	go func() {
		<-signalChan
		fmt.Println("Received termination signal. Exiting...")
		c.CloseAction()
		os.Exit(0)
	}()
}
func (c Close) CloseFFin() {
	if len(c.closeFin.FileFin) > 0 {
		for _, v := range c.closeFin.FileFin {
			if v != nil {
				if err := v.Close(); err != nil {
					fmt.Println(fmt.Sprintf("%v report: close file fail. error is %v",arg.ProcessName, err))
					return
				}
			}
		}
	}
	if c.closeFin.XlsFin != nil {
		if err := c.closeFin.XlsFin.Close(); err != nil {
			fmt.Println(fmt.Sprintf("%v report: close file fail. error is %v", arg.ProcessName, err))
			return
		}
	}

}
func (c Close) CloseAction() {
	var (
		t   Er.TableConnEr
		err error
	)
	if t, err = Er.CActive(Er.ConnActive{DBType: c.Dsn.Name}); err != nil {
		return
	}
	t.Close(c.Dsn.DsnS)
	c.CloseFFin()
	//删除miss rows使用的临时目录
	global.FilePathExistDelete("tmp")
}

func GetClose(m map[string]any, db map[string]*sql.DB, fileFin []*os.File) Close {
	var c Close
	// 将映射转换为JSON字符串
	jsonData, err := json.Marshal(m)
	if err != nil {
		//global.Wlog.Error(fmt.Sprintf("(%d) %s map[string]any strconv json fail. error info is %v", 1, "[close active]", err))
		return c
	}
	// 将JSON字符串解码为结构体
	err = json.Unmarshal(jsonData, &c)
	if err != nil {
		//global.Wlog.Error(fmt.Sprintf("(%d) %s json strconv struct fail. error info is %v", 1, "[close active]", err))
		return c
	}
	//map[string]interface{}不能直接映射指针类型
	c.Dsn.DsnS = db
	c.closeFin.FileFin = fileFin
	return c
}
